import { Component, OnInit } from '@angular/core';
import {MapUtil} from "../../../util/map-util";
import {MsgConstants} from "../../../constants/constants";
import {MsgResult} from "../../../models/msg-result";
import {OneDialogService} from "../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../util/response-util";
import {BigScreenUtilService} from "../big-screen-util.service";

declare var BMap;
declare var BMapLib;
declare var echarts;
declare var $;

@Component({
  selector: 'app-big-screen-dashboard',
  templateUrl: './big-screen-dashboard.component.html',
  styleUrls: ['./big-screen-dashboard.component.css']
})
export class BigScreenDashboardComponent implements OnInit {

  blist: Array<any> = [];
  districtLoading:any = 0;
  map: any;

  constructor(
    private mapUtil : MapUtil,
    private dialogService: OneDialogService,
    private bigScreenUtil: BigScreenUtilService,
    private responseUtil: ResponseUtil
  ) { }

  ngOnInit() {
    this.mapUtil.loadMapScript( ()=> this.init());
    this.mapUtil.loadMapLib('http://api.map.baidu.com/library/AreaRestriction/1.2/src/AreaRestriction_min.js');
    this.getNewAccount();
    this.getStatisticsVisits();
    this.getTerminalVisitType();
    this.getVisitNumber();
  }
  /**
   * 初始化地图
   */
  init () {
    this.map = new BMap.Map("dvMap", { enableMapClick: false,minZoom:10,maxZoom:11 }); // 创建地图实例，禁止点击地图底图
    let mapStyle = [
      {
        "featureType": "poi",
        "elementType": "all",
        "stylers": {
          "visibility": "on"
        }
      },
      {
        "featureType": "land",
        "elementType": "geometry",
        "stylers": {
          "color": "#24252b"
        }
      },
      {
        "featureType": "road",
        "elementType": "geometry",
        "stylers": {
          "color": "#171717",
          "hue": "#171717",
          "weight": "0.1",
          "lightness": -6,
          "saturation": -15
        }
      },
      {
        "featureType": "highway",
        "elementType": "labels.icon",
        "stylers": {
          "visibility": "off"
        }
      },
      {
        "featureType": "building",
        "elementType": "geometry",
        "stylers": {
          "color": "#2a2b2e"
        }
      },
      {
        "featureType": "highway",
        "elementType": "all",
        "stylers": {
          "lightness": -42,
          "saturation": -91
        }
      },
      {
        "featureType": "arterial",
        "elementType": "geometry",
        "stylers": {
          "lightness": -77,
          "saturation": -94
        }
      },
      {
        "featureType": "green",
        "elementType": "geometry",
        "stylers": {
          "color": "#1b1b1b"
        }
      },
      {
        "featureType": "subway",
        "elementType": "geometry.stroke",
        "stylers": {
          "color": "#181818"
        }
      },
      {
        "featureType": "railway",
        "elementType": "geometry",
        "stylers": {
          "lightness": -52
        }
      },
      {
        "featureType": "all",
        "elementType": "labels.text.stroke",
        "stylers": {
          "color": "#313131"
        }
      },
      {
        "featureType": "all",
        "elementType": "labels.text.fill",
        "stylers": {
          "color": "#8b8787"
        }
      },
      {
        "featureType": "manmade",
        "elementType": "geometry",
        "stylers": {
          "color": "#1b1b1b"
        }
      },
      {
        "featureType": "local",
        "elementType": "geometry",
        "stylers": {
          "lightness": -75,
          "saturation": -91
        }
      },
      {
        "featureType": "subway",
        "elementType": "geometry",
        "stylers": {
          "lightness": -65
        }
      },
      {
        "featureType": "railway",
        "elementType": "all",
        "stylers": {
          "lightness": -40
        }
      },
      {
        "featureType": "road",
        "elementType": "geometry",
        "stylers": {
          "color": "#171717",
          "hue": "#041e3b",
          "weight": "1.0",
          "lightness": -12,
          "saturation": -15
        }
      },
      {
        "featureType": "water",
        "elementType": "geometry",
        "stylers": {
          "color": "#041e3b",
          "hue": "#041e3b",
          "weight": "0.1",
          "lightness": -12,
          "saturation": -15
        }
      }
    ];
    this.map.setMapStyle({
      styleJson: mapStyle
    });

    // this.map.disableDragging();//禁止拖动
    this.map.enableScrollWheelZoom(true);
    this.map.disableDoubleClickZoom();//禁止双击缩放


    setTimeout( () => {
      this.getBoundary();
    }, 1000);
  }

  getBoundary() {
    this.addDistrict("郑州");
  }
  /**
   * 添加行政区划
   * @param {} districtName 行政区划名
   * @returns  无返回值
   */
  addDistrict(districtName) {
    //使用计数器来控制加载过程
    this.districtLoading++;
    let bdary = new BMap.Boundary();
    bdary.get(districtName,  (rs) => {       //获取行政区域
      let count = rs.boundaries.length; //行政区域的点有多少个
      if (count === 0) {
        alert('未能获取当前输入行政区域');
        return;
      }
      for (let i = 0; i < count; i++) {
        this.blist.push({ points: rs.boundaries[i], name: districtName });
      };
      //加载完成区域点后计数器-1
      this.districtLoading--;
      if (this.districtLoading == 0) {
        //全加载完成后画端点
        this.drawBoundary();
      }
    });
  }
  drawBoundary() {
    //包含所有区域的点数组
    let pointArray = [];

    /*画遮蔽层的相关方法
     *思路: 首先在中国地图最外画一圈，圈住理论上所有的中国领土，然后再将每个闭合区域合并进来，并全部连到西北角。
     *      这样就做出了一个经过多次西北角的闭合多边形*/
    //定义中国东南西北端点，作为第一层
    let pNW = { lat: 59.0, lng: 73.0 }
    let pNE = { lat: 59.0, lng: 136.0 }
    let pSE = { lat: 3.0, lng: 136.0 }
    let pSW = { lat: 3.0, lng: 73.0 }
    //向数组中添加一次闭合多边形，并将西北角再加一次作为之后画闭合区域的起点
    let pArray = [];
    pArray.push(pNW);
    pArray.push(pSW);
    pArray.push(pSE);
    pArray.push(pNE);
    pArray.push(pNW);
    //循环添加各闭合区域
    for (let i = 0; i < this.blist.length; i++) {
      //添加多边形层并显示
      let ply = new BMap.Polygon(this.blist[i].points, { strokeWeight: 5, strokeColor: "#2A5BDC", fillOpacity: 0.01, fillColor: " transparent" }); //建立多边形覆盖物
      ply.name = this.blist[i].name;
      this.map.addOverlay(ply);

      //将点增加到视野范围内
      let path = ply.getPath();
      pointArray = pointArray.concat(path);
      //将闭合区域加到遮蔽层上，每次添加完后要再加一次西北角作为下次添加的起点和最后一次的终点
      pArray = pArray.concat(path);
      pArray.push(pArray[0]);
    }

    //限定显示区域，需要引用api库
    let boundply = new BMap.Polygon(pointArray);
    // console.log(boundply.getBounds());
    let bound = new BMap.Bounds( new BMap.Point(pSE.lng,pSE.lat) ,  new BMap.Point(pSW.lng,pSW.lat));
    // console.log(bound);
    BMapLib.AreaRestriction.setBounds(this.map, boundply.getBounds());
    // BMapLib.AreaRestriction.setBounds(this.map, bound);
    this.map.setViewport(pointArray);    //调整视野

    //添加遮蔽层
    let plyall = new BMap.Polygon(pArray, { strokeOpacity: 0.0000001, strokeColor: "#000000", strokeWeight: 0.00001, fillColor: "#070E27", fillOpacity: 1 }); //建立多边形覆盖物
    this.map.addOverlay(plyall);
  }

  /**
   * 获取日访问总量
   */
  getDailyVisits() {
    this.bigScreenUtil.getStatisticsDailyVisitsByTime().subscribe(
      result => this.responseUtil.success(result, this.processDailyVisitsResulr),
      error => this.responseUtil.error(error)
    );
  }

  processDailyVisitsResulr = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      console.log("日访问总量：" + JSON.stringify(result.data));
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.modalError(result.message);
    }
  }

  /**
   * 获取访问量
   */
  getStatisticsVisits() {
    this.bigScreenUtil.getStatisticsVisitsByTime().subscribe(
      resuult => this.responseUtil.success(resuult, this.processStatisticsVisitsResult),
      error => this.responseUtil.error(error)
    );
  }

  processStatisticsVisitsResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      console.log('某月的日访问量:'+JSON.stringify(result.data));
      this.statisticsVisitsEcharts(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.modalError(result.message);
    }
  }

  /**
   *  时间段访问量折线柱状图
   * @param data ：数据
   */
  statisticsVisitsEcharts(data) {
    // 基于准备好的dom，初始化echarts图表
    let myChart = echarts.init(document.getElementById('visitCount'));
    let option = {
      tooltip: {
        trigger: 'axis',
        formatter:function(params){
          params[0].value = params[0].value?params[0].value:"-";
          return params[0].name+" </br>"+params[0].seriesName+":"+params[0].value;
        }
      },
      legend: {
        selectedMode: false,
        data: data.legendList,
        textStyle:{
          color:'#fff'
        },
        top:20
      },
      color:['#5A84E5','#195AEE'],
      calculable: true,
      xAxis: [
        {
          type: 'category',
          data:data.timeList,
          axisLine:{
            lineStyle:{
              color:'#fff'
            }
          },
          axisLabel:{
            color:'#fff'
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          axisLine:{
            lineStyle:{
              color:'#fff'
            }
          },
          axisLabel:{
            color:'#fff'
          }
        }
      ],
      series: [
        {
          name: data.visitType,
          type: 'bar',
          barMaxWidth:40,
          data: data.visitsList,

          markLine: {
            data: [
              {type: 'average', name: '平均值'}
            ]
          }
        },
        {
          name: data.visitType,
          type: 'line',
          data: data.visitsList,
          markLine: {
            data: [
              {type: 'average', name: '平均值'}
            ]
          }
        }
      ]
    };
    // 为echarts对象加载数据
    myChart.setOption(option);
  }


  /**
   *  获取新增账户量
   */
  getNewAccount() {
    let params = 'startTime='+'2017-11-01 00:00:00'+'&endTime='+'2017-11-08 14:30:38'+'&timeType='+'month';
    this.bigScreenUtil.getNewAccountByTime().subscribe(
      resuult => this.responseUtil.success(resuult, this.processNewAccountResult),
      error => this.responseUtil.error(error)
    );
  }

  processNewAccountResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      console.log(JSON.stringify(result.data));
      this.NewAccountEcharts(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.modalError(result.message);
    }
  }

  /**
   * 时间段新增账户折线柱状图
   * @param data
   */
  NewAccountEcharts(data) {
    // 基于准备好的dom，初始化echarts图表
    let myChart = echarts.init(document.getElementById('newUserCount'));

    let option = {
      tooltip: {
        trigger: 'axis',
        formatter:function(params){
          params[0].value = params[0].value?params[0].value:"-";
          return params[0].name+" </br>"+params[0].seriesName+":"+params[0].value;
        }
      },
      legend: {
        selectedMode: false,
        data: data.legendList,
        textStyle:{
          color:'#fff'
        },
        top:20
      },
      color:['#5A84E5','#195AEE'],
      calculable: true,
      xAxis: [
        {
          type: 'category',
          data:data.timeList,
          axisLine:{
            lineStyle:{
              color:'#fff'
            }
          },
          axisLabel:{
            color:'#fff'
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          axisLine:{
            lineStyle:{
              color:'#fff'
            }
          },
          axisLabel:{
            color:'#fff'
          }
        }
      ],
      series: [
        {
          name: data.visitType,
          type: 'bar',
          barMaxWidth:40,
          data: data.dayNewAccountList,
          markLine: {
            data: [
              {type: 'average', name: '平均值'}
            ]
          }
        } , {
          name: data.visitType,
          type: 'line',
          data: data.dayNewAccountList,
          markLine: {
            data: [
              {type: 'average', name: '平均值'}
            ]
          }
        }
      ]
    };
    // 为echarts对象加载数据
    myChart.setOption(option);
  }

  /**
   *  统计区段访问次数总量
   */
  getVisitNumber() {
    // let params = 'startTime='+'2017-11-01 00:00:00'+'&endTime='+'2017-11-08 14:30:38'+'&timeType='+'month'
    this.bigScreenUtil.getVisitNumber().subscribe(
      resuult => this.responseUtil.success(resuult, this.processVisitNumberResult),
      error => this.responseUtil.error(error)
    );
  }

  processVisitNumberResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      console.log("访问次数："+JSON.stringify(result.data[0]));
      this.visitNumberEcharts(result.data[0]);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.modalError(result.message);
    }
  }

  /**
   * 区间访问次数访问量折线柱状图
   * @param data
   */
  visitNumberEcharts(data) {
    // 基于准备好的dom，初始化echarts图表
    let myChart = echarts.init(document.getElementById('userVisitCount'));

    let option = {
      tooltip: {
        trigger: 'axis',
        formatter:function(params){
          params[0].value = params[0].value?params[0].value:"-";
          return params[0].name+" </br>"+params[0].seriesName+":"+params[0].value;
        }
      },
      legend: {
        selectedMode: false,
        data: ['区段访问次数'],
        textStyle:{
          color:'#fff'
        },
        top:20
      },
      color:['#5A84E5','#195AEE'],
      calculable: true,
      xAxis: [
        {
          type: 'category',
          data:data.spacingList,
          axisLine:{
            lineStyle:{
              color:'#fff'
            }
          },
          axisLabel:{
            color:'#fff'
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          axisLine:{
            lineStyle:{
              color:'#fff'
            }
          },
          axisLabel:{
            color:'#fff'
          }
        }
      ],
      series: [
        {
          name: '访问量',
          type: 'bar',
          barMaxWidth:40,
          data: data.visitNum,
          markLine: {
            data: [
              {type: 'average', name: '平均值'}
            ]
          }
        }, {
          name: '访问量',
          type: 'line',
          data: data.visitNum,
        }
      ]
    };
    // 为echarts对象加载数据
    myChart.setOption(option);
  }

  /**
   *  获取用户访问终端的类型数据
   */
  getTerminalVisitType() {
    this.bigScreenUtil.getTerminalVisitType().subscribe(
      resuult => this.responseUtil.success(resuult, this.processTerminalVisitResult),
      error => this.responseUtil.error(error)
    );
  }

  processTerminalVisitResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      console.log(JSON.stringify(result.data));
      this.terminalVisitTypeEcharts(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.modalError(result.message);
    }
  }

  /**
   *
   * @param data
   */
  terminalVisitTypeEcharts(data){
    // 基于准备好的dom，初始化echarts图表
    let myChart = echarts.init(document.getElementById('terminalType'));
    let option = {
      tooltip : {
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
      },
      color:['#5A84E5','#195AEE'],
      legend: {
        selectedMode: false,
        orient:'vertical',
        left: 10,
        top : 'center',
        data:['PC','APP'],
        textStyle:{
          color:'#fff'
        }
      },
      calculable : true,
      series : [
        {
          name:'访问来源',
          type:'pie',
          radius : '55%',
          center: ['50%', '60%'],
          data:data
        }
      ]
    };

    myChart.setOption(option);
  }
}
